package com.ken.zeratul.commons.spring;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Optional;

public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public static <T> T getBean(Class<T> tcls){
        try {
            return Optional.ofNullable(applicationContext)
                    .map(context -> context.getBean(tcls))
                    .orElse(null);
        } catch (Exception e) {
            return null;
        }
    }

    public static <T> T getBean(String name){
        try {
            return (T) Optional.ofNullable(applicationContext)
                    .map(context -> context.getBean(name))
                    .orElse(null);
        } catch (Exception e) {
            return null;
        }
    }

    public static <T> T getProxy(T obj){
        return (T) getBean(obj.getClass());
    }

    public static ApplicationContext getContext() {
        return applicationContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }
}
